`
We can migrate the job from the background to the foreground by issuing the
fg command and the job ID (Listing 2-39).
$ fg %1
sleep 100
Listing 2-39
Sending a job to the foreground
At this point, the sleep command is occupying the terminal, since it’s
running in the foreground. You can press CTRL+Z to suspend the process, which
will produce the following output in the jobs table:
[1]+ Stopped sleep 100
To send this job to the background again in a running state, use the bg
command with the job ID (Listing 2-40).
$ bg %1
[1]+ sleep 100 &
Listing 2-40
Sending a job to the background
Keeping a Job Running After Logout
Whether you send a job to the background or are running a job in the
foreground, the process won’t survive if you close the terminal or log out. If you
close the terminal, the process will receive a SIGHUP signal and terminate.
What if we wanted to keep running a script in the background even after
we’ve logged out of the terminal window or closed it? To do so, we could start a
script or command with the nohup (no hangup) command prepended (Listing 2-
41).
$ nohup ./my_script.sh &
Listing 2-41
Keeping a script running after closing the terminal or logging out
The nohup command will create a file named nohup.out with standard output
stream data. So, make sure you delete this file if you don't want to leave any traces
on the disk.
There are additional ways to run background scripts, such as by plugging into
system and service managers like systemd, which provide additional features, such
as monitoring that the process is running, restarting it if it isn’t, and capturing
failures. We encourage you to read more about systemd if you have such use-cases
at https://man7.org/linux/man-pages/man1/init.1.html.
Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks